/********************************************************************************
Copyright (C) 2016  International Ltd.
Copyright (C) 2022 - 2023, Phytium Technology Co., Ltd. All rights reserved.<BR>

SPDX-License-Identifier: BSD-2-Clause-Patent

*******************************************************************************/

#include "BiosUpdate.h"


//UINT8        *mBufferPtr;
EFI_MTFTP4_TOKEN     Mtftp4Token;

EFI_STATUS FlushFlash(UINTN Address, UINT32 BufferSizeInBytes)
{
#if 0
  EFI_STATUS Status;
  EFI_CPU_ARCH_PROTOCOL    *gCpu;

  // Get the Cpu protocol for later use
  Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&gCpu);
  if(EFI_ERROR(Status)) {
    DEBUG((EFI_D_INFO, "%a() Line=%d\n", __FUNCTION__, __LINE__));
    return Status;
  }

  Status = gCpu->FlushDataCache (gCpu, Address, BufferSizeInBytes, EfiCpuFlushTypeWriteBack);
  if(EFI_ERROR(Status)) {
    DEBUG((EFI_D_INFO, "%a() Line=%d\n", __FUNCTION__, __LINE__));
    return Status;
  }
#endif

  WriteBackDataCacheRange ((VOID *)(UINTN)Address, (UINTN)BufferSizeInBytes);
  return EFI_SUCCESS;
}


/*can write 256 bytes one time*/
static inline
EFI_STATUS
SpiWrite(
  IN UINTN            Address,
  IN VOID             *Buffer,
  IN UINT32           BufferSizeInBytes
  )
{
  UINT32 cmd_id = 0;
  UINT32 Index;
  UINT32 *TemBuffer = Buffer;
  EFI_STATUS Status;


  if(BufferSizeInBytes > 256) {
    DEBUG((EFI_D_ERROR, "Max Len is 256\n"));
    return EFI_INVALID_PARAMETER;
  }

  if(BufferSizeInBytes % 4 != 0) {
    DEBUG((EFI_D_ERROR, "Len must aligne 4 bytes\n"));
    return EFI_INVALID_PARAMETER;
  }

  if(Address % 4 != 0) {
    DEBUG((EFI_D_ERROR, "Address not aligne 4 byte \n"));
    return EFI_INVALID_PARAMETER;
  }

  cmd_id = mCmd_Pp;
  if(Address >= 0x1000000){
    MmioWrite32(mNorFlashControlBase + REG_CMD_PORT, 0x400000 | (cmd_id << 24) | BIT12);
  }else{
    MmioWrite32(mNorFlashControlBase + REG_CMD_PORT, 0x400000 | (cmd_id << 24));
  }
  MmioWrite32(mNorFlashControlBase + REG_LD_PORT, 0x1);
  asm volatile ("isb sy":::"cc");
  asm volatile ("dsb sy":::"cc");

  cmd_id = mCmd_Write;
  if(Address >= 0x1000000){
    cmd_id = mCmd_Write16;
    MmioWrite32(mNorFlashControlBase + REG_WR_CFG, 0x000208 | (cmd_id << 24) | BIT4);
  }else{
    MmioWrite32(mNorFlashControlBase + REG_WR_CFG, 0x000208 | (cmd_id << 24));
  }

  for(Index = 0; Index < BufferSizeInBytes/4; Index++) {
    MmioWrite32(Address + Index * 4, TemBuffer[Index]);
  }
  Status = FlushFlash(Address, BufferSizeInBytes);
  asm volatile ("isb sy":::"cc");
  asm volatile ("dsb sy":::"cc");

  MmioWrite32(mNorFlashControlBase + REG_FLUSH_REG, 0x1);

  asm volatile ("isb sy":::"cc");
  asm volatile ("dsb sy":::"cc");

  MmioWrite32(mNorFlashControlBase + REG_WR_CFG, 0x0);

  return Status;
}

/*
static inline void SPI_Write_Word(UINTN Address, UINT32 Value)
{
  UINT32 cmd_id = 0;
  if (Value == 0xffffffff)
    return;

  if(Address % 4 != 0) {
	  DEBUG((EFI_D_ERROR, "Address not aligne 4 byte \n"));
  }

  cmd_id = mCmd_Pp;
  MmioWrite32(mNorFlashControlBase + REG_CMD_PORT, 0x400000 | (cmd_id << 24));
  MmioWrite32(mNorFlashControlBase + REG_LD_PORT, 0x1);
  asm volatile ("isb sy":::"cc");
  asm volatile ("dsb sy":::"cc");
  cmd_id = mCmd_Write;
  MmioWrite32(mNorFlashControlBase + REG_WR_CFG, 0x000208 | (cmd_id << 24) | 0x10);
  MmioWrite32(Address, Value);
  asm volatile ("isb sy":::"cc");
  asm volatile ("dsb sy":::"cc");
  MmioWrite32(mNorFlashControlBase + REG_FLUSH_REG, 0x1);
  asm volatile ("isb sy":::"cc");
  asm volatile ("dsb sy":::"cc");
  MmioWrite32(mNorFlashControlBase + REG_WR_CFG, 0x0);
  flush_flash(Address, Value);
}
*/
static inline void SPI_Erase_Sector(UINTN BlockAddress)
{
  UINT32 cmd_id;

  cmd_id = mCmd_Pp;
  if(BlockAddress >= 0x1000000){
    MmioWrite32(mNorFlashControlBase + REG_CMD_PORT, 0x400000 | (cmd_id << 24) | BIT12);
  }else{
    MmioWrite32(mNorFlashControlBase + REG_CMD_PORT, 0x400000 | (cmd_id << 24));
  }
  MmioWrite32(mNorFlashControlBase + REG_LD_PORT, 0x1);
  asm volatile ("isb sy":::"cc");
  asm volatile ("dsb sy":::"cc");

  cmd_id = mCmd_Eares;
  if(BlockAddress >= 0x1000000){
    cmd_id = mCmd_Eares16;
    MmioWrite32(mNorFlashControlBase + REG_CMD_PORT, 0x408000 |(cmd_id << 24));
  }else{
    MmioWrite32(mNorFlashControlBase + REG_CMD_PORT, 0x408000 |(cmd_id << 24));
  }
  MmioWrite32(mNorFlashControlBase + REG_ADDR_PORT, BlockAddress);
  MmioWrite32(mNorFlashControlBase + REG_LD_PORT, 0x1);
  asm volatile ("isb sy":::"cc");
  asm volatile ("dsb sy":::"cc");
}


/**
  Fixup internal data so that EFI can be call in virtual mode.
  Call the passed in Child Notify event and convert any pointers in
  lib to virtual mode.

  @param[in]    Event   The Event that is being processed
  @param[in]    Context Event Context
**/


EFI_STATUS
NorFlashPlatformGetDevices (
  OUT NOR_FLASH_DESCRIPTION_PHYTIUM   **NorFlashDevices,
  OUT UINT32                  *Count
  )
{

  if ((NorFlashDevices == NULL) || (Count == NULL)) {
    return EFI_INVALID_PARAMETER;
  }

  *NorFlashDevices = mNorFlashDevices;
  *Count = NOR_FLASH_DEVICE_COUNT;

  return EFI_SUCCESS;
}

EFI_STATUS
NorFlashPlatformRead (
  IN UINTN            Address,
  IN VOID             *Buffer,
  IN UINT32           BufferSizeInBytes
  )
{
  UINTN RDCFG;
  DEBUG((EFI_D_BLKIO, "NorFlashPlatformRead: Address: 0x%lx Buffer:0x%p Len:0x%x\n", Address, Buffer, BufferSizeInBytes));

  if(Address >= 0x1000000){
  RDCFG         = MmioRead32(mNorFlashControlBase+RD_CFG);

  //DEBUG((EFI_D_INFO,"The RD_CFG is 0x%lx\n",RDCFG));
  RDCFG         
|= 0x13080000;
  MmioWrite32(mNorFlashControlBase+RD_CFG,RDCFG);

  //RDCFG         = MmioRead32(mNorFlashControlBase+RD_CFG);
  //DEBUG((EFI_D_INFO,"The RD_CFG is 0x%lx\n",RDCFG));
  }

  CopyMem ((VOID *)Buffer, (VOID *)Address, BufferSizeInBytes);

  return EFI_SUCCESS;
}

EFI_STATUS
NorFlashPlatformEraseSingleBlock (
  IN UINTN            BlockAddress
  )
{
  DEBUG((EFI_D_BLKIO, "NorFlashPlatformEraseSingleBlock: BlockAddress: 0x%lx,mNorFlashControlBase:%lx\n", BlockAddress,mNorFlashControlBase));

  SPI_Erase_Sector(BlockAddress);

  return EFI_SUCCESS;
}

EFI_STATUS
NorFlashPlatformWrite (
  IN UINTN            Address,
  IN VOID             *Buffer,
  IN UINT32           BufferSizeInBytes
  )
{
  UINT32 Index = 0, Remainder = 0, Quotient = 0;
  EFI_STATUS Status;
  UINTN TmpAddress = Address;

  DEBUG((EFI_D_BLKIO, "NorFlashPlatformWrite: Address: 0x%x Len:0x%x\n", Address, BufferSizeInBytes));
  Remainder = BufferSizeInBytes % 256;
  Quotient = BufferSizeInBytes / 256;

  if(BufferSizeInBytes <= 256) {
    Status = SpiWrite(TmpAddress, Buffer, BufferSizeInBytes);
  } else {
    for(Index = 0; Index < Quotient; Index++) {
        Status = SpiWrite(TmpAddress, Buffer, 256);
        TmpAddress += 256;
        Buffer += 256;
    }

    if(Remainder != 0) {
      Status = SpiWrite(TmpAddress, Buffer, Remainder);
    }
  }

  if(EFI_ERROR(Status)) {
      DEBUG((EFI_D_ERROR, "%a() Line=%d\n", __FUNCTION__, __LINE__));
      ASSERT_EFI_ERROR(Status);
  }

  return EFI_SUCCESS;
}



EFI_STATUS
Erase (
  IN UINT64                  Offset,
  IN UINT64                  Length
) {
  EFI_STATUS     Status;
  UINT64         Index;
  UINT64         Count;

  Status = EFI_SUCCESS;
  if ((Length % SIZE_64KB) == 0) {
    Count = Length / SIZE_64KB;
    for (Index = 0; Index < Count; Index ++) {
      NorFlashPlatformEraseSingleBlock (Offset);
      Offset += SIZE_64KB;
    }
  } else {
    Status = EFI_INVALID_PARAMETER;
  }

  return Status;
}

EFI_STATUS
Write (
  IN  UINT64                 Offset,
  IN  UINT8                  *Buffer,
  IN  UINT64                 Length
) {
  EFI_STATUS     Status;
  
  if (Length % 4 || Offset % 4) {
    DEBUG ((EFI_D_ERROR, "Error input for spi program!!Need check!!\n"));
    return EFI_INVALID_PARAMETER;
  }
  Status = NorFlashPlatformWrite(Offset, Buffer, Length);
 
  return Status;
}


EFI_STATUS
Read (
  IN UINT64                  Offset,
  IN OUT UINT8               *Buffer,
  IN UINT64                  Length
) {

  NorFlashPlatformRead (Offset, Buffer, Length);
  
  return EFI_SUCCESS;
}

EFI_STATUS
EraseWrite (
  IN  UINT64                 Offset,
  IN  UINT8                  *Buffer,
  IN  UINT64                 Length
) {
  EFI_STATUS      Status;
  UINTN           Index;
  UINTN           Count;

  Status = EFI_SUCCESS;
  Count = Length / SIZE_64KB;
  for (Index = 0; Index < Count; Index ++) {
    Status = Erase (Offset + Index * SIZE_64KB, SIZE_64KB);
    if (EFI_ERROR(Status)) {
      break;
    }
    Status = Write (Offset + Index * SIZE_64KB, Buffer + Index * SIZE_64KB, SIZE_64KB);
    if (EFI_ERROR(Status)) {
      break;
    }
  }
  return Status;
}




EFI_STATUS
UpdateSpi (
  IN UINTN                     Address,
  IN UINTN                     Size,
  IN CHAR16                    *String
)
{
  EFI_STATUS  Status;
  UINTN       Index;
  UINTN       Count;
  VOID        *TempBuffer = NULL;

  TempBuffer = AllocatePool(SIZE_64KB);
  Status = EFI_SUCCESS;
  Count  = (Size / SIZE_64KB);
  // make sure Address & Size is 64k align
  if ((Address % SIZE_64KB) || (Size % SIZE_64KB)) {
    Count ++;
    Address = Address & (~0xFFFF);
  }
  //Print(L"Mtftp4Token.Buffer address %p\n",Mtftp4Token.Buffer);
  Print(L"%s%02d%%%",String, 1);
  for (Index = 0; Index < Count; Index ++) {
    if (TempBuffer != NULL) {
      Read (
        Address + Index * SIZE_64KB,
        TempBuffer,
        SIZE_64KB
        );
      if (CompareMem(TempBuffer, Mtftp4Token.Buffer + Index * SIZE_64KB, SIZE_64KB) == 0) {
        Print(L"\r%s %02d%%",String, ((Index + 1) * 100) / Count);
        continue;
      }
    }
    EraseWrite (
      Address + Index * SIZE_64KB,
      Mtftp4Token.Buffer + Index * SIZE_64KB,
      SIZE_64KB
      );
    if (EFI_ERROR(Status)) {
      Print(L"\r%s Fail!\n",String);
      goto ProExit;
    }
    Print(L"\r%s %02d%%",String, ((Index + 1) * 100) / Count);
  }
  Print(L"\r%s Success!\n",String);

ProExit:
  if (TempBuffer != NULL) {
    FreePool (TempBuffer);
  }
  return Status;
}

SHELL_STATUS
EFIAPI
ShellCommandRunBiosUpdate (
  IN EFI_HANDLE         ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  SHELL_STATUS            ShellStatus;
  EFI_STATUS              Status;
  LIST_ENTRY              *CheckPackage;
  CHAR16                  *ProblemParam;
  UINTN                   ParamCount;
  CONST CHAR16            *UserNicName;
  BOOLEAN                 NicFound;
  CONST CHAR16            *ValueStr;
  CONST CHAR16            *RemoteFilePath;
  CHAR8                   *AsciiRemoteFilePath;
  UINTN                   FilePathSize;
  CONST CHAR16            *Walker;
  EFI_MTFTP4_CONFIG_DATA  Mtftp4ConfigData;
  EFI_HANDLE              *Handles;
  UINTN                   HandleCount;
  UINTN                   NicNumber;
  CHAR16                  NicName[IP4_CONFIG2_INTERFACE_INFO_NAME_LENGTH];
  EFI_HANDLE              ControllerHandle;
  EFI_HANDLE              Mtftp4ChildHandle;
  EFI_MTFTP4_PROTOCOL     *Mtftp4;
  UINTN                   FileSize;
  UINT16                  BlockSize;
  UINT16                  WindowSize;
  //UINT8                   *MD5BufAfterDownload = NULL;
  //UINT8                   *ReadFlashBufer      = NULL;
  //UINT8                   *MD5BufAfterFlash    = NULL;

  ShellStatus         = SHELL_INVALID_PARAMETER;
  ProblemParam        = NULL;
  NicFound            = FALSE;
  AsciiRemoteFilePath = NULL;
  Handles             = NULL;
  FileSize            = 0;
  BlockSize           = MTFTP_DEFAULT_BLKSIZE;
  WindowSize          = MTFTP_DEFAULT_WINDOWSIZE;

  //
  // Initialize the Shell library (we must be in non-auto-init...)
  //
  Status = ShellInitialize ();
  if (EFI_ERROR (Status)) {
    ASSERT_EFI_ERROR (Status);
    return SHELL_ABORTED;
  }

  //
  // Parse the command line.
  //
  Status = ShellCommandLineParse (ParamList, &CheckPackage, &ProblemParam, TRUE);
  if (EFI_ERROR (Status)) {
    if ((Status == EFI_VOLUME_CORRUPTED) &&
        (ProblemParam != NULL) ) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_GEN_PROBLEM), ShellBiosUpdateHiiHandle,
        L"updatebios", ProblemParam
        );
      FreePool (ProblemParam);
    } else {
      ASSERT (FALSE);
    }
    goto Error;
  }

  //
  // Check the number of parameters
  //
  ParamCount = ShellCommandLineGetCount (CheckPackage);
  if (ParamCount > 4) {
    ShellPrintHiiEx (
      -1, -1, NULL, STRING_TOKEN (STR_GEN_TOO_MANY),
      ShellBiosUpdateHiiHandle, L"updatebios"
      );
    goto Error;
  }
  if (ParamCount < 3) {
    ShellPrintHiiEx (
      -1, -1, NULL, STRING_TOKEN (STR_GEN_TOO_FEW),
      ShellBiosUpdateHiiHandle, L"updatebios"
      );
    goto Error;
  }

  CopyMem (&Mtftp4ConfigData, &DefaultMtftp4ConfigData, sizeof (EFI_MTFTP4_CONFIG_DATA));

  //
  // Check the host IPv4 address
  //
  ValueStr = ShellCommandLineGetRawValue (CheckPackage, 1);
  Status = NetLibStrToIp4 (ValueStr, &Mtftp4ConfigData.ServerIp);
  if (EFI_ERROR (Status)) {
    ShellPrintHiiEx (
      -1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV),
      ShellBiosUpdateHiiHandle, L"updatebios", ValueStr
    );
    goto Error;
  }

  RemoteFilePath = ShellCommandLineGetRawValue (CheckPackage, 2);
  ASSERT(RemoteFilePath != NULL);
  FilePathSize = StrLen (RemoteFilePath) + 1;
  AsciiRemoteFilePath = AllocatePool (FilePathSize);
  if (AsciiRemoteFilePath == NULL) {
    ShellStatus = SHELL_OUT_OF_RESOURCES;
    goto Error;
  }
  UnicodeStrToAsciiStrS (RemoteFilePath, AsciiRemoteFilePath, FilePathSize);

  if (ParamCount == 4) {
    mLocalFilePath = ShellCommandLineGetRawValue (CheckPackage, 3);
  } else {
    Walker = RemoteFilePath + StrLen (RemoteFilePath);
    while ((--Walker) >= RemoteFilePath) {
      if ((*Walker == L'\\') ||
          (*Walker == L'/' )    ) {
        break;
      }
    }
    mLocalFilePath = Walker + 1;
  }

  //
  // Get the name of the Network Interface Card to be used if any.
  //
  UserNicName = ShellCommandLineGetValue (CheckPackage, L"-i");

  ValueStr = ShellCommandLineGetValue (CheckPackage, L"-l");
  if (ValueStr != NULL) {
    if (!StringToUint16 (ValueStr, &Mtftp4ConfigData.LocalPort)) {
      goto Error;
    }
  }

  ValueStr = ShellCommandLineGetValue (CheckPackage, L"-r");
  if (ValueStr != NULL) {
    if (!StringToUint16 (ValueStr, &Mtftp4ConfigData.InitialServerPort)) {
      goto Error;
    }
  }

  ValueStr = ShellCommandLineGetValue (CheckPackage, L"-c");
  if (ValueStr != NULL) {
    if (!StringToUint16 (ValueStr, &Mtftp4ConfigData.TryCount)) {
      goto Error;
    }

    if (Mtftp4ConfigData.TryCount == 0) {
      Mtftp4ConfigData.TryCount = 6;
    }
  }

  ValueStr = ShellCommandLineGetValue (CheckPackage, L"-t");
  if (ValueStr != NULL) {
    if (!StringToUint16 (ValueStr, &Mtftp4ConfigData.TimeoutValue)) {
      goto Error;
    }
    if (Mtftp4ConfigData.TimeoutValue == 0) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV),
        ShellBiosUpdateHiiHandle, L"updatebios", ValueStr
      );
      goto Error;
    }
  }

  ValueStr = ShellCommandLineGetValue (CheckPackage, L"-s");
  if (ValueStr != NULL) {
    if (!StringToUint16 (ValueStr, &BlockSize)) {
      goto Error;
    }
    if (BlockSize < MTFTP_MIN_BLKSIZE || BlockSize > MTFTP_MAX_BLKSIZE) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV),
        ShellBiosUpdateHiiHandle, L"updatebios", ValueStr
      );
      goto Error;
    }
  }

  ValueStr = ShellCommandLineGetValue (CheckPackage, L"-w");
  if (ValueStr != NULL) {
    if (!StringToUint16 (ValueStr, &WindowSize)) {
      goto Error;
    }
    if (WindowSize < MTFTP_MIN_WINDOWSIZE || WindowSize > MTFTP_MAX_WINDOWSIZE) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV),
        ShellBiosUpdateHiiHandle, L"updatebios", ValueStr
      );
      goto Error;
    }
  }

  //
  // Locate all MTFTP4 Service Binding protocols
  //
  ShellStatus = SHELL_NOT_FOUND;
  Status = gBS->LocateHandleBuffer (
                 ByProtocol,
                 &gEfiManagedNetworkServiceBindingProtocolGuid,
                 NULL,
                 &HandleCount,
                 &Handles
                 );
  if (EFI_ERROR (Status) || (HandleCount == 0)) {
    ShellPrintHiiEx (
      -1, -1, NULL, STRING_TOKEN (STR_TFTP_ERR_NO_NIC),
      ShellBiosUpdateHiiHandle
    );
    goto Error;
  }

  for (NicNumber = 0;
       (NicNumber < HandleCount) && (ShellStatus != SHELL_SUCCESS);
       NicNumber++) {
    ControllerHandle = Handles[NicNumber];

    Status = GetNicName (ControllerHandle, NicNumber, NicName);
    if (EFI_ERROR (Status)) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_TFTP_ERR_NIC_NAME),
        ShellBiosUpdateHiiHandle, NicNumber, Status
      );
      continue;
    }

    if (UserNicName != NULL) {
      if (StrCmp (NicName, UserNicName) != 0) {
        continue;
      }
      NicFound = TRUE;
    }

    Status = CreateServiceChildAndOpenProtocol (
               ControllerHandle,
               &gEfiMtftp4ServiceBindingProtocolGuid,
               &gEfiMtftp4ProtocolGuid,
               &Mtftp4ChildHandle,
               (VOID**)&Mtftp4
               );
    if (EFI_ERROR (Status)) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_TFTP_ERR_OPEN_PROTOCOL),
        ShellBiosUpdateHiiHandle, NicName, Status
      );
      continue;
    }

    Status = Mtftp4->Configure (Mtftp4, &Mtftp4ConfigData);
    if (EFI_ERROR (Status)) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_TFTP_ERR_CONFIGURE),
        ShellBiosUpdateHiiHandle, NicName, Status
      );
      goto NextHandle;
    }

    Status = GetFileSize (Mtftp4, AsciiRemoteFilePath, &FileSize);
    if (EFI_ERROR (Status)) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_TFTP_ERR_FILE_SIZE),
        ShellBiosUpdateHiiHandle, RemoteFilePath, NicName, Status
      );
      goto NextHandle;
    }

    Mtftp4Token.Buffer  = AllocatePool(FileSize);
    //MD5BufAfterDownload = AllocatePool(16);
    //MD5BufAfterFlash    = AllocatePool(16);
    Print (L"Mtftp4Token.Buffer Allocate : %p , FileSize : %d\n",Mtftp4Token.Buffer, FileSize);

    Status = DownloadFile (Mtftp4, RemoteFilePath, AsciiRemoteFilePath, FileSize, BlockSize, WindowSize);
    if (EFI_ERROR (Status)) {
      ShellPrintHiiEx (
        -1, -1, NULL, STRING_TOKEN (STR_TFTP_ERR_DOWNLOAD),
        ShellBiosUpdateHiiHandle, RemoteFilePath, NicName, Status
      );
      goto NextHandle;
    }

    Status = UpdateSpi (
               0,
               FileSize,
               L"Updating bios."
               );

/*
    //Status = Md5HashAll(Mtftp4Token.Buffer,FileSize,MD5BufAfterDownload);
    if (!Md5HashAll(Mtftp4Token.Buffer,FileSize,MD5BufAfterDownload)){
      Print (L"Failed to calculate the download file hash\n");
    }
    Status = UpdateSpi (
               0,
               FileSize,
               L"Updating bios."
               );
    ReadFlashBufer = AllocatePool(FileSize);
    Read(0,ReadFlashBufer,FileSize);

    //Status = Md5HashAll(ReadFlashBufer,FileSize,MD5BufAfterFlash);
    if (!Md5HashAll(ReadFlashBufer,FileSize,MD5BufAfterFlash)){
      Print (L"Failed to calculate the flash file hash\n");
    }

    while (CompareMem(MD5BufAfterDownload,MD5BufAfterFlash,FileSize) != 0){
      Print (L"Downloading and buring files are not inconsistent\n");
      Status = UpdateSpi (
               0,
               FileSize,
               L"Updating bios."
               );
      Read(0,ReadFlashBufer,FileSize);
      Md5HashAll(ReadFlashBufer,FileSize,MD5BufAfterFlash);
    }
    Print (L"File verification is consistent before and after buring\n");

*/
    SystemReboot();
    ShellStatus = SHELL_SUCCESS;


  //
  //
  //
    NextHandle:

    CloseProtocolAndDestroyServiceChild (
      ControllerHandle,
      &gEfiMtftp4ServiceBindingProtocolGuid,
      &gEfiMtftp4ProtocolGuid,
      Mtftp4ChildHandle
      );
  }

  if ((UserNicName != NULL) && (!NicFound)) {
    ShellPrintHiiEx (
      -1, -1, NULL, STRING_TOKEN (STR_TFTP_ERR_NIC_NOT_FOUND),
      ShellBiosUpdateHiiHandle, UserNicName
    );
  }

  Error:

  ShellCommandLineFreeVarList (CheckPackage);
  if (AsciiRemoteFilePath != NULL) {
    FreePool (AsciiRemoteFilePath);
  }
  if (Handles != NULL) {
    FreePool (Handles);
  }

  if ((ShellStatus != SHELL_SUCCESS) && (EFI_ERROR(Status))) {
    ShellStatus = Status & ~MAX_BIT;
  }

  return ShellStatus;
}

/**
  Check and convert the UINT16 option values of the 'tftp' command

  @param[in]  ValueStr  Value as an Unicode encoded string
  @param[out] Value     UINT16 value

  @return     TRUE      The value was returned.
  @return     FALSE     A parsing error occured.
**/
STATIC
BOOLEAN
StringToUint16 (
  IN   CONST CHAR16  *ValueStr,
  OUT  UINT16        *Value
  )
{
  UINTN  Val;

  Val = ShellStrToUintn (ValueStr);
  if (Val > MAX_UINT16) {
    ShellPrintHiiEx (
      -1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV),
      ShellBiosUpdateHiiHandle, L"updatebios", ValueStr
    );
    return FALSE;
  }

  *Value = (UINT16)Val;
  return TRUE;
}

/**
  Get the name of the NIC.

  @param[in]   ControllerHandle  The network physical device handle.
  @param[in]   NicNumber         The network physical device number.
  @param[out]  NicName           Address where to store the NIC name.
                                 The memory area has to be at least
                                 IP4_CONFIG2_INTERFACE_INFO_NAME_LENGTH
                                 double byte wide.

  @return  EFI_SUCCESS  The name of the NIC was returned.
  @return  Others       The creation of the child for the Managed
                        Network Service failed or the opening of
                        the Managed Network Protocol failed or
                        the operational parameters for the
                        Managed Network Protocol could not be
                        read.
**/
STATIC
EFI_STATUS
GetNicName (
  IN   EFI_HANDLE  ControllerHandle,
  IN   UINTN       NicNumber,
  OUT  CHAR16      *NicName
  )
{
  EFI_STATUS                    Status;
  EFI_HANDLE                    MnpHandle;
  EFI_MANAGED_NETWORK_PROTOCOL  *Mnp;
  EFI_SIMPLE_NETWORK_MODE       SnpMode;

  Status = CreateServiceChildAndOpenProtocol (
             ControllerHandle,
             &gEfiManagedNetworkServiceBindingProtocolGuid,
             &gEfiManagedNetworkProtocolGuid,
             &MnpHandle,
             (VOID**)&Mnp
             );
  if (EFI_ERROR (Status)) {
    goto Error;
  }

  Status = Mnp->GetModeData (Mnp, NULL, &SnpMode);
  if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) {
    goto Error;
  }

  UnicodeSPrint (
    NicName,
    IP4_CONFIG2_INTERFACE_INFO_NAME_LENGTH,
    SnpMode.IfType == NET_IFTYPE_ETHERNET ?
    L"eth%d" :
    L"unk%d" ,
    NicNumber
    );

  Status = EFI_SUCCESS;

Error:

  if (MnpHandle != NULL) {
    CloseProtocolAndDestroyServiceChild (
      ControllerHandle,
      &gEfiManagedNetworkServiceBindingProtocolGuid,
      &gEfiManagedNetworkProtocolGuid,
      MnpHandle
      );
  }

  return Status;
}

/**
  Create a child for the service identified by its service binding protocol GUID
  and get from the child the interface of the protocol identified by its GUID.

  @param[in]   ControllerHandle            Controller handle.
  @param[in]   ServiceBindingProtocolGuid  Service binding protocol GUID of the
                                           service to be created.
  @param[in]   ProtocolGuid                GUID of the protocol to be open.
  @param[out]  ChildHandle                 Address where the handler of the
                                           created child is returned. NULL is
                                           returned in case of error.
  @param[out]  Interface                   Address where a pointer to the
                                           protocol interface is returned in
                                           case of success.

  @return  EFI_SUCCESS  The child was created and the protocol opened.
  @return  Others       Either the creation of the child or the opening
                        of the protocol failed.
**/
STATIC
EFI_STATUS
CreateServiceChildAndOpenProtocol (
  IN   EFI_HANDLE  ControllerHandle,
  IN   EFI_GUID    *ServiceBindingProtocolGuid,
  IN   EFI_GUID    *ProtocolGuid,
  OUT  EFI_HANDLE  *ChildHandle,
  OUT  VOID        **Interface
  )
{
  EFI_STATUS  Status;

  *ChildHandle = NULL;
  Status = NetLibCreateServiceChild (
             ControllerHandle,
             gImageHandle,
             ServiceBindingProtocolGuid,
             ChildHandle
             );
  if (!EFI_ERROR (Status)) {
    Status = gBS->OpenProtocol (
                    *ChildHandle,
                    ProtocolGuid,
                    Interface,
                    gImageHandle,
                    ControllerHandle,
                    EFI_OPEN_PROTOCOL_GET_PROTOCOL
                    );
    if (EFI_ERROR (Status)) {
      NetLibDestroyServiceChild (
        ControllerHandle,
        gImageHandle,
        ServiceBindingProtocolGuid,
        *ChildHandle
        );
      *ChildHandle = NULL;
    }
  }

  return Status;
}

/**
  Close the protocol identified by its GUID on the child handle of the service
  identified by its service binding protocol GUID, then destroy the child
  handle.

  @param[in]  ControllerHandle            Controller handle.
  @param[in]  ServiceBindingProtocolGuid  Service binding protocol GUID of the
                                          service to be destroyed.
  @param[in]  ProtocolGuid                GUID of the protocol to be closed.
  @param[in]  ChildHandle                 Handle of the child to be destroyed.

**/
STATIC
VOID
CloseProtocolAndDestroyServiceChild (
  IN  EFI_HANDLE  ControllerHandle,
  IN  EFI_GUID    *ServiceBindingProtocolGuid,
  IN  EFI_GUID    *ProtocolGuid,
  IN  EFI_HANDLE  ChildHandle
  )
{
  gBS->CloseProtocol (
         ChildHandle,
         ProtocolGuid,
         gImageHandle,
         ControllerHandle
         );

  NetLibDestroyServiceChild (
    ControllerHandle,
    gImageHandle,
    ServiceBindingProtocolGuid,
    ChildHandle
    );
}

/**
  Worker function that gets the size in numbers of bytes of a file from a TFTP
  server before to download the file.

  @param[in]   Mtftp4    MTFTP4 protocol interface
  @param[in]   FilePath  Path of the file, ASCII encoded
  @param[out]  FileSize  Address where to store the file size in number of
                         bytes.

  @retval  EFI_SUCCESS      The size of the file was returned.
  @retval  EFI_UNSUPPORTED  The server does not support the "tsize" option.
  @retval  Others           Error when retrieving the information from the server
                            (see EFI_MTFTP4_PROTOCOL.GetInfo() status codes)
                            or error when parsing the response of the server.
**/
STATIC
EFI_STATUS
GetFileSize (
  IN   EFI_MTFTP4_PROTOCOL  *Mtftp4,
  IN   CONST CHAR8          *FilePath,
  OUT  UINTN                *FileSize
  )
{
  EFI_STATUS         Status;
  EFI_MTFTP4_OPTION  ReqOpt[1];
  EFI_MTFTP4_PACKET  *Packet;
  UINT32             PktLen;
  EFI_MTFTP4_OPTION  *TableOfOptions;
  EFI_MTFTP4_OPTION  *Option;
  UINT32             OptCnt;
  UINT8              OptBuf[128];

  ReqOpt[0].OptionStr = (UINT8*)"tsize";
  OptBuf[0] = '0';
  OptBuf[1] = 0;
  ReqOpt[0].ValueStr = OptBuf;

  Status = Mtftp4->GetInfo (
             Mtftp4,
             NULL,
             (UINT8*)FilePath,
             NULL,
             1,
             ReqOpt,
             &PktLen,
             &Packet
             );

  if (EFI_ERROR (Status)) {
    goto Error;
  }

  Status = Mtftp4->ParseOptions (
                     Mtftp4,
                     PktLen,
                     Packet,
                     (UINT32 *) &OptCnt,
                     &TableOfOptions
                     );
  if (EFI_ERROR (Status)) {
    goto Error;
  }

  Option = TableOfOptions;
  while (OptCnt != 0) {
    if (AsciiStrnCmp ((CHAR8 *)Option->OptionStr, "tsize", 5) == 0) {
      *FileSize = AsciiStrDecimalToUintn ((CHAR8 *)Option->ValueStr);
      break;
    }
    OptCnt--;
    Option++;
  }
  FreePool (TableOfOptions);

  if (OptCnt == 0) {
    Status = EFI_UNSUPPORTED;
  }

Error :

  return Status;
}

/**
  Worker function that download the data of a file from a TFTP server given
  the path of the file and its size.

  @param[in]   Mtftp4         MTFTP4 protocol interface
  @param[in]   FilePath       Path of the file, Unicode encoded
  @param[in]   AsciiFilePath  Path of the file, ASCII encoded
  @param[in]   FileSize       Size of the file in number of bytes
  @param[in]   BlockSize      Value of the TFTP blksize option
  @param[in]   WindowSize     Value of the TFTP window size option

  @retval  EFI_SUCCESS           The file was downloaded.
  @retval  EFI_OUT_OF_RESOURCES  A memory allocation failed.
  @retval  Others                The downloading of the file from the server failed
                                 (see EFI_MTFTP4_PROTOCOL.ReadFile() status codes).

**/
STATIC
EFI_STATUS
DownloadFile (
  IN   EFI_MTFTP4_PROTOCOL  *Mtftp4,
  IN   CONST CHAR16         *FilePath,
  IN   CONST CHAR8          *AsciiFilePath,
  IN   UINTN                FileSize,
  IN   UINT16               BlockSize,
  IN   UINT16               WindowSize
  )
{
  EFI_STATUS            Status;
  DOWNLOAD_CONTEXT      *TftpContext;
  //EFI_MTFTP4_TOKEN      Mtftp4Token;
  UINT8                 BlksizeBuf[10];
  UINT8                 WindowsizeBuf[10];


  TftpContext = AllocatePool (sizeof (DOWNLOAD_CONTEXT));
  if (TftpContext == NULL) {
    Status = EFI_OUT_OF_RESOURCES;
    goto Error;
  }
  TftpContext->FileSize = FileSize;
  TftpContext->DownloadedNbOfBytes   = 0;
  TftpContext->LastReportedNbOfBytes = 0;

  Mtftp4Token.Filename    = (UINT8*)AsciiFilePath;
  Mtftp4Token.CheckPacket = CheckPacket;
  Mtftp4Token.Context     = (VOID*)TftpContext;
  Mtftp4Token.OptionCount = 0;
  Mtftp4Token.OptionList  = AllocatePool (sizeof (EFI_MTFTP4_OPTION) * 2);
  Mtftp4Token.BufferSize  = FileSize;
  if (Mtftp4Token.OptionList == NULL) {
    Status = EFI_OUT_OF_RESOURCES;
    goto Error;
  }

  if (BlockSize != MTFTP_DEFAULT_BLKSIZE) {
    Mtftp4Token.OptionList[Mtftp4Token.OptionCount].OptionStr = (UINT8 *) "blksize";
    AsciiSPrint ((CHAR8 *) BlksizeBuf, sizeof (BlksizeBuf), "%d", BlockSize);
    Mtftp4Token.OptionList[Mtftp4Token.OptionCount].ValueStr  = BlksizeBuf;
    Mtftp4Token.OptionCount ++;
  }

  if (WindowSize != MTFTP_DEFAULT_WINDOWSIZE) {
    Mtftp4Token.OptionList[Mtftp4Token.OptionCount].OptionStr = (UINT8 *) "windowsize";
    AsciiSPrint ((CHAR8 *) WindowsizeBuf, sizeof (WindowsizeBuf), "%d", WindowSize);
    Mtftp4Token.OptionList[Mtftp4Token.OptionCount].ValueStr  = WindowsizeBuf;
    Mtftp4Token.OptionCount ++;
  }

  ShellPrintHiiEx (
    -1, -1, NULL, STRING_TOKEN (STR_TFTP_DOWNLOADING),
    ShellBiosUpdateHiiHandle, FilePath
    );
  //Print(L"Mtftp4Token.Buffer address %p\n",Mtftp4Token.Buffer);

  Status = Mtftp4->ReadFile (Mtftp4, &Mtftp4Token);
  ShellPrintHiiEx (
    -1, -1, NULL, STRING_TOKEN (STR_GEN_CRLF),
    ShellBiosUpdateHiiHandle
    );
  Print(L"Mtftp4Token.Buffer address %p\n",Mtftp4Token.Buffer);



Error :
  if (TftpContext != NULL) {
    FreePool (TftpContext);
  }

  if (Mtftp4Token.OptionList != NULL) {
    FreePool (Mtftp4Token.OptionList);
  }

  return Status;
}

/**
  Update the progress of a file download
  This procedure is called each time a new TFTP packet is received.

  @param[in]  This       MTFTP4 protocol interface
  @param[in]  Token      Parameters for the download of the file
  @param[in]  PacketLen  Length of the packet
  @param[in]  Packet     Address of the packet

  @retval  EFI_SUCCESS  All packets are accepted.

**/
STATIC
EFI_STATUS
EFIAPI
CheckPacket (
  IN EFI_MTFTP4_PROTOCOL  *This,
  IN EFI_MTFTP4_TOKEN     *Token,
  IN UINT16               PacketLen,
  IN EFI_MTFTP4_PACKET    *Packet
  )
{
  DOWNLOAD_CONTEXT  *Context;
  CHAR16            Progress[UPDATEBIOS_PROGRESS_MESSAGE_SIZE];
  UINTN             NbOfKb;
  UINTN             Index;
  UINTN             LastStep;
  UINTN             Step;
  UINTN             DownloadLen;
  EFI_STATUS        Status;

  if ((NTOHS (Packet->OpCode)) != EFI_MTFTP4_OPCODE_DATA) {
    return EFI_SUCCESS;
  }

  Context = (DOWNLOAD_CONTEXT*)Token->Context;

  //
  // The data in the packet are prepended with two UINT16 :
  // . OpCode = EFI_MTFTP4_OPCODE_DATA
  // . Block  = the number of this block of data
  //
  DownloadLen = (UINTN)PacketLen - sizeof (Packet->OpCode) - sizeof (Packet->Data.Block);


  if (Context->DownloadedNbOfBytes == 0) {
    ShellPrintEx (-1, -1, L"%s       0 Kb", mUpdateBiosProgressFrame);
  }

  Context->DownloadedNbOfBytes += DownloadLen;
  NbOfKb = Context->DownloadedNbOfBytes / 1024;

  Progress[0] = L'\0';
  LastStep  = (Context->LastReportedNbOfBytes * UPDATEBIOS_PROGRESS_SLIDER_STEPS) / Context->FileSize;
  Step      = (Context->DownloadedNbOfBytes * UPDATEBIOS_PROGRESS_SLIDER_STEPS) / Context->FileSize;

  if (Step <= LastStep) {
    return EFI_SUCCESS;
  }

  ShellPrintEx (-1, -1, L"%s", mUpdateBiosProgressDelete);

  Status = StrCpyS (Progress, UPDATEBIOS_PROGRESS_MESSAGE_SIZE, mUpdateBiosProgressFrame);
  if (EFI_ERROR(Status)) {
    return Status;
  }
  for (Index = 1; Index < Step; Index++) {
    Progress[Index] = L'=';
  }
  Progress[Step] = L'>';

  UnicodeSPrint (
    Progress + (sizeof (mUpdateBiosProgressFrame) / sizeof (CHAR16)) - 1,
    sizeof (Progress) - sizeof (mUpdateBiosProgressFrame),
    L" %7d Kb",
    NbOfKb
    );
  Context->LastReportedNbOfBytes = Context->DownloadedNbOfBytes;

  ShellPrintEx (-1, -1, L"%s", Progress);

  return EFI_SUCCESS;
}

/**
  Retrive HII package list from ImageHandle and publish to HII database.

  @param ImageHandle            The image handle of the process.

  @return HII handle.
**/
EFI_HANDLE
InitializeHiiPackage (
  EFI_HANDLE                  ImageHandle
  )
{
  EFI_STATUS                  Status;
  EFI_HII_PACKAGE_LIST_HEADER *PackageList;
  EFI_HANDLE                  HiiHandle;

  //
  // Retrieve HII package list from ImageHandle
  //
  Status = gBS->OpenProtocol (
                  ImageHandle,
                  &gEfiHiiPackageListProtocolGuid,
                  (VOID **)&PackageList,
                  ImageHandle,
                  NULL,
                  EFI_OPEN_PROTOCOL_GET_PROTOCOL
                  );
  ASSERT_EFI_ERROR (Status);
  if (EFI_ERROR (Status)) {
    return NULL;
  }

  //
  // Publish HII package list to HII Database.
  //
  Status = gHiiDatabase->NewPackageList (
                           gHiiDatabase,
                           PackageList,
                           NULL,
                           &HiiHandle
                           );
  ASSERT_EFI_ERROR (Status);
  if (EFI_ERROR (Status)) {
    return NULL;
  }
  return HiiHandle;
}

/*
STATIC
VOID
Usage (
  VOID
  )
{
  Print (L"Basic E2000Update commands:\n"
  );
}

SHELL_STATUS
EFIAPI
ShellCommandRunBiosUpdate (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS              Status;
  LIST_ENTRY              *CheckPackage;
  CHAR16                  *ProblemParam;

  Status = ShellInitialize ();
  if (EFI_ERROR (Status)) {
    Print (L"Error - failed to initialize shell\n");
    return SHELL_ABORTED;
  }
  //Print (L"update new bios111111111.\n");

  Status = ShellCommandLineParse (ParamList, &CheckPackage, &ProblemParam, TRUE);
  if (EFI_ERROR (Status)) {
    Print (L"Error - failed to parse command line\n");
    return SHELL_ABORTED;
  }

  if (ShellCommandLineGetFlag (CheckPackage, L"biosupdate")) {
    //
    // update
    //
    Print (L"update new bios.\n");
    RunTftp();
    return SHELL_SUCCESS;
  }

  if (ShellCommandLineGetFlag (CheckPackage, L"help")) {
    Usage();
    return SHELL_SUCCESS;
  }

  Status = SHELL_SUCCESS;
  return Status;
}
*/
EFI_STATUS
EFIAPI
ShellBiosUpdateLibConstructor (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{

  ShellBiosUpdateHiiHandle = NULL;

  ShellBiosUpdateHiiHandle = HiiAddPackages (
                          &gShellBiosUpdateHiiGuid, gImageHandle,
                          UefiShellBiosUpdateLibStrings, NULL
                          );
  if (ShellBiosUpdateHiiHandle == NULL) {
    Print (L"Filed to add Hii package\n");
    return EFI_DEVICE_ERROR;
  }
  ShellCommandRegisterCommandName (
     L"updatebios", ShellCommandRunBiosUpdate, ShellCommandGetManFileNameBiosUpdate, 0,
     L"updatebios", TRUE , ShellBiosUpdateHiiHandle, STRING_TOKEN (STR_GET_HELP_BIOSUPDATE)
     );
  mNorFlashControlBase = FixedPcdGet64 (PcdSpiControllerBase);

  return EFI_SUCCESS;
}

EFI_STATUS
EFIAPI
ShellBiosUpdateLibDestructor (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{

  if (ShellBiosUpdateHiiHandle != NULL) {
    HiiRemovePackages (ShellBiosUpdateHiiHandle);
  }
  return EFI_SUCCESS;
}
